package com.xp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xp.entity.User;
import com.xp.service.UserService;
import com.xp.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 * 
 * @author AI Assistant
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@Validated
@Tag(name = "用户管理", description = "用户增删改查、状态管理等接口")
public class UserController {

    private final UserService userService;

    /**
     * 分页查询用户列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询用户", description = "根据条件分页查询用户列表")
    public Result<IPage<User>> getUserPage(
            @Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", required = true) @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "邮箱") @RequestParam(required = false) String email,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        
        Page<User> page = new Page<>(current, size);
        return userService.getUserPage(page, username, email, status);
    }

    /**
     * 获取所有启用的用户
     */
    @GetMapping("/enabled")
    @Operation(summary = "获取启用用户", description = "获取所有启用状态的用户列表")
    public Result<List<User>> getEnabledUsers() {
        return userService.getEnabledUsers();
    }

    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    public Result<User> getUserById(@Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        return userService.getUserById(id);
    }

    /**
     * 创建用户
     */
    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    public Result<Object> createUser(@Valid @RequestBody UserRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setRealName(request.getRealName());
        user.setStatus(request.getStatus());
        
        return userService.createUser(user);
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public Result<Object> updateUser(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id,
            @Valid @RequestBody UserUpdateRequest request) {
        
        User user = new User();
        user.setUsername(request.getUsername());
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setRealName(request.getRealName());
        user.setStatus(request.getStatus());
        
        // 只有提供了密码才更新密码
        if (request.getPassword() != null && !request.getPassword().trim().isEmpty()) {
            user.setPassword(request.getPassword());
        }
        
        return userService.updateUser(id, user);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "删除指定用户")
    public Result<Object> deleteUser(@Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        return userService.deleteUser(id);
    }

    /**
     * 更新用户状态
     */
    @PutMapping("/{id}/status")
    @Operation(summary = "更新用户状态", description = "启用或禁用用户")
    public Result<Object> updateUserStatus(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id,
            @Valid @RequestBody StatusRequest request) {
        return userService.updateUserStatus(id, request.getStatus());
    }

    /**
     * 用户创建请求DTO
     */
    public static class UserRequest {
        
        @NotBlank(message = "用户名不能为空")
        @Parameter(description = "用户名", required = true)
        private String username;

        @NotBlank(message = "密码不能为空")
        @Parameter(description = "密码", required = true)
        private String password;

        @Parameter(description = "邮箱")
        private String email;

        @Parameter(description = "手机号")
        private String phone;

        @Parameter(description = "真实姓名")
        private String realName;

        @Parameter(description = "状态（1-启用，0-禁用）")
        private Integer status;

        // Getter and Setter methods
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getRealName() {
            return realName;
        }

        public void setRealName(String realName) {
            this.realName = realName;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }

    /**
     * 用户更新请求DTO
     */
    public static class UserUpdateRequest {
        
        @NotBlank(message = "用户名不能为空")
        @Parameter(description = "用户名", required = true)
        private String username;

        @Parameter(description = "密码（可选，不提供则不更新）")
        private String password;

        @Parameter(description = "邮箱")
        private String email;

        @Parameter(description = "手机号")
        private String phone;

        @Parameter(description = "真实姓名")
        private String realName;

        @Parameter(description = "状态（1-启用，0-禁用）")
        private Integer status;

        // Getter and Setter methods
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getRealName() {
            return realName;
        }

        public void setRealName(String realName) {
            this.realName = realName;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }

    /**
     * 状态更新请求DTO
     */
    public static class StatusRequest {
        
        @NotNull(message = "状态不能为空")
        @Parameter(description = "状态（1-启用，0-禁用）", required = true)
        private Integer status;

        // Getter and Setter methods
        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }
}